from rest_framework import serializers
from course.models import CourseDirectionModel, CourseCategoryModel, CourseModel, TeacherModel, CourseChapterModel


# 课程方向的序列化器
class CourseDirectionModelSerializer(serializers.ModelSerializer):
    class Meta():
        model = CourseDirectionModel
        fields = ['id', 'name']


# 课程分类的序列化器
class CourseCategoryModelSerializer(serializers.ModelSerializer):
    class Meta():
        model = CourseCategoryModel
        fields = ['id', 'name']


# 课程列表序列化器
class CourseModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseModel
        fields = '__all__'


# 教师信息序列化器
class TeacherModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = TeacherModel
        fields = ['id', 'name', 'get_role_display', 'title', 'signature', 'avatar', 'brief']


# 课程详情序列化器
class CourseRetrieveSerializer(serializers.ModelSerializer):

    direction_name = serializers.CharField(source='direction.name', read_only=True)
    category_name = serializers.CharField(source='category.name', read_only=True)
    teacher_name = serializers.CharField(source='teacher.name', read_only=True)
    teacher = TeacherModelSerializer()

    class Meta:
        model = CourseModel
        fields = ['name', 'course_cover', 'course_video', 'course_type', 'get_level_display',
                  'status', 'description', 'pub_date', 'period', 'attachment_path', 'attachment_link',
                  'students', 'lessons', 'pub_lessons', 'price', 'credit', 'direction', 'category',
                  'teacher', 'direction_name', 'category_name', 'teacher_name', 'discount']


# 课程章节、课时
class CourseChapterSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseChapterModel
        fields = ['id', 'orders', 'name', 'summary', 'pub_date', 'course', 'get_lesson_list']


from drf_haystack.serializers import HaystackSerializer
from course.search_indexes import CourseIndex


class  CourseIndexHaystackSerializer(HaystackSerializer):
    """课程搜索的序列化器"""
    class Meta:
        index_classes = [CourseIndex]
        fields = ["text", "id", "name", "course_cover", "get_level_display", "students", "get_status_display", "pub_lessons", "price", "discount", "orders"]

    def to_representation(self, instance):
        """用于指定返回数据的字段的"""
        # 课程的图片，在这里通过elasticsearch提供的，所以不会提供图片地址左边的域名的。因此在这里手动拼接
        instance.course_cover = f'http://127.0.0.1:8000/uploads/{instance.course_cover}'
        return super().to_representation(instance)

